//
//  UserAcount.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/13.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit

class UserAcount: NSObject,NSCoding {

    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
            
            
        }
    }
    
    
    var expires_date: NSDate?
    var uid: String?
    var name: String?
    var avatar_large: String?
    
    
    
    
    init(dict: [String : AnyObject])  {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    
    override  var  description: String {
        
        get {
            
            let keys  = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
            let dict = self.dictionaryWithValuesForKeys(keys)
            
            return dict.description
        }
    }
  
    func saveAccount(){
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        
    }
    
    class func loadUserAccount() -> UserAcount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAcount {
            
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                
                return account

            }
        }
        
        return nil
    }
    
    
    //解归档操作
   required init?(coder aDecoder: NSCoder) {
    
    access_token = aDecoder.decodeObjectForKey("access_token") as? String
    expires_in = aDecoder.decodeDoubleForKey("expires_in")
    uid = aDecoder.decodeObjectForKey("uid") as? String
    name = aDecoder.decodeObjectForKey("name") as? String
    avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    
    }
   
    //归档操作
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        
    }
    
    
    
    
}
